package and.xunger.com.myfirstdemo;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

import java.util.ArrayList;

import and.xunger.com.myfirstdemo.tablayout.TabFragment;

public class TabLayoutActivity extends AppCompatActivity {

  private ArrayList<Fragment> data = new ArrayList<>();
  private ViewPager viewPager;
  private TabLayout tabLayout;
  private FragmentPagerAdapter pagerAdapter;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tab_layout);

    initView();
    initFragmentData();
    fillViewPager();
    fillTabLayout();
  }

  private void initView() {
    tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    viewPager = (ViewPager) findViewById(R.id.view_pager);

  }

  private void initFragmentData() {
    for (int i = 0; i < 10; i++) {
      TabFragment tabFragment = new TabFragment();
      data.add(tabFragment);
    }
  }

  private void fillViewPager() {
    pagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
      @Override
      public Fragment getItem(int position) {
        return data.get(position);
      }

      @Override
      public int getCount() {
        return data.size();
      }

      @Override
      public CharSequence getPageTitle(int position) {
        return "标题" + ++position;
      }
    };
    viewPager.setAdapter(pagerAdapter);
  }

  private void fillTabLayout() {
    tabLayout.setupWithViewPager(viewPager);
  }
}
